package com.anruisi.hxmes.auth.config;


import com.anruisi.hxmes.auth.entity.SysUser;
import com.anruisi.hxmes.auth.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author cmy
 * @date 2021/5/20 10:11
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException{
        SysUser user = sysUserService.selectUserByName(s);
        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误!");
        }
        if (!user.isEnabled()) {
            throw new DisabledException("该账户已被禁用，请联系管理员!");
        }
        Set<String> roles = new HashSet<>(sysUserService.selectSysRoleByUserId(user.getId()));
        List<GrantedAuthority> grantedAuthorities = roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());

        user.setAuthorities(grantedAuthorities);
        return user;
    }


}
